import { useState, useEffect, Fragment } from 'react';
import { ThreeHeaderC, SceneCardC, SecondHeaderC } from '@/src/components';
import uuid from 'es6-uuid';
import { sceneToRisk, sceneTree } from '../constantConfig';
import AddTableC from './addTableC';
import styles from './index.less';
import { filterAndSortTreeData } from './disposeDataFn';

// 寻找选中的节点和其所有的父节点
const findParent = (data, targetId, result) => {
  for (const item of data) {
    if (item.id === targetId) {
      // 将查找到的目标数据加入结果数组中
      result.unshift(item.id);
      return true;
    }
    if (item.children?.length) {
      // 根据查找到的结果往上找父级节点
      const isFind = findParent(item.children, targetId, result);
      if (isFind) {
        result.unshift(item.id);
        return true;
      }
    }
  }
  // 走到这说明没找到目标
  return false;
};
// 将key,value 转换成 [key]：value
const formatFactorList = (data = []) => {
  const arr = [];
  data.forEach((item) => {
    const obj = {};
    item.forEach((x) => {
      obj.key = uuid(16);
      obj[x.key] = x.value;
    });
    arr.push(obj);
  });
  return arr;
};
const SceneDetailC = (props) => {
  const { sceneList, riskFactor = [] } = props;
  const [selectIdList, setSelectIdList] = useState([]); // 所有选中的节点 包含所有父节点
  const [treeData, setTreeData] = useState([]); // 情景项 树形结构

  const setSelectFlag = (id, arr = []) => {
    let flag = false;
    for (let index = 0; index < arr.length; index++) {
      const item = arr[index];
      if (id === item.id) {
        item.show = true;
        flag = true;
        return flag;
      } else {
        // 第一级没有匹配成功 如果有子项 则继续递归，如果无子项 就设置为false
        if (item.children?.length) {
          // 有子项的继续
          const childFlag = setSelectFlag(id, item.children);
          if (childFlag) return flag; // 如果子项匹配成功则退出
        } else {
          item.show = false;
        }
      }
    }
    return flag;
  };
  useEffect(() => {
    const selectIds = [];
    // 给情景项根据第二步的右侧 排序 方法通用
    const sortData = filterAndSortTreeData(_.cloneDeep(sceneTree), sceneList);
    setTreeData(sortData);
    const tempArr = _.cloneDeep(sortData);
    sceneList.forEach((sceneId) => {
      findParent(tempArr, sceneId, selectIds);
    });
    const newArr = Array.from(new Set([...selectIds]));
    //  获取选中的情景项及所有父节点
    setSelectIdList(newArr);
  }, [sceneList, riskFactor]);

  // 获取factor因子列表并展示
  const getItemFactor = (sceneId) => {
    const itemFactorList = sceneToRisk.filter((item) => sceneId === item.sceneId);
    // 拿到每个情景项目对应的因子列表
    if (!itemFactorList?.length) return null;
    return itemFactorList[0]?.riskFactor?.map((factor) => {
      const arrElement = riskFactor.filter((y) => factor.id === y.id);

      if (!arrElement?.length) return null;
      factor.tableData = arrElement[0].setting?.body || [];
      // 渲染因子表格
      return (
        <div key={factor.id} style={{ padding: '0px 15px' }}>
          <div style={{ margin: ' 15px 0', paddingLeft: '20px' }}>{`${factor.path}-${factor.name}`}</div>
          <AddTableC id={factor.id} tableData={formatFactorList(JSON.parse(JSON.stringify(factor.tableData)))} showType='view' />
        </div>
      );
    });
  };
  // 加载每个情景项卡片
  const renderItem = (scene) => {
    return (
      <div key={scene.id} style={{ marginBottom: '15px' }}>
        <SceneCardC title={scene.name} id={scene.id} initOpen={true} content={getItemFactor(scene.id)} />
      </div>
    );
  };
  // 加载页面
  const renderView = () => {
    return (
      <Fragment>
        {treeData.map((scene) => {
          if (selectIdList.includes(scene.id)) {
            return (
              <div key={`${scene.id}`}>
                {/* 第一层标题 */}
                <SecondHeaderC title={scene.name} />
                {scene.children?.map((child) => {
                  if (selectIdList.includes(child.id)) {
                    if (child.children?.length) {
                      return (
                        <div key={`${child.id}`}>
                          {/* 第二层标题 */}
                          <ThreeHeaderC title={child.name} />
                          {child.children.map((x) => {
                            // 这是子项
                            return renderItem(x);
                          })}
                        </div>
                      );
                    }
                    // 这是子项
                    return renderItem(child);
                  } else {
                    return null;
                  }
                })}
              </div>
            );
          }
          return null;
        })}
      </Fragment>
    );
  };
  return <div>{renderView()}</div>;
};
export { formatFactorList };
export default SceneDetailC;
